<?php

/**
 * 购物车操作类
 * @package  htdocs
 * @subpackage  module/base
 * @version 1.0
 */
quanli_require('module/base/promotionHandler.class.php');

class cartHandler {

    private $g_shop;

    public function __construct( &$g_shop ) {
        $this->g_shop = $g_shop;
    }

    private function createCartStructure() {

        $bill_array = array(

            'bill_no' => null,

            'bill_status' => 0,

            'change_time' => null,

            'message' => null,

            'goods' => array(),

            'master' => array()

        );

        return $bill_array;

    }

    /**
     * 生成购物车商品数组结构
     * @param array $goods_array 商品数组
     * @param int $type 类型：1、普通商品 2、赠品 6、闪购 8、超值选购 9、积分换购
     * @return array
     */
    private function createCartGoodsStructure( $goods_array, $type = 1 ) {

        if ($type == 1) { 
            $goods_array['addPoints'] = 0;
            $goods_array['goods_from'] = 1;
            $goods_array['goods_groupID'] = 0;
            $goods_array['price'] = $goods_array['salePrice'];
        } else if ($type == 2) {
            $goods_array['addPoints'] = 0;
            $goods_array['salePoints'] = 0;
            $goods_array['goodsWeight'] = 0;
            $goods_array['goodsLength'] = 0;
            $goods_array['goodsWidth'] = 0;
            $goods_array['goodsHeight'] = 0;
        } else if ($type == 6) {
            $goods_array['goods_from'] = 6;
            $goods_array['goods_groupID'] = 0;
            $goods_array['addPoints'] = 0;
            $goods_array['salePoints'] = 0;
        }else if( $type == 5 ){
            $goods_array['goods_groupID'] = 0;
            $goods_array['goods_from'] = 5;
        } else if ( $type == 8 ) {
        	$goods_array['goods_from'] = 8;
        } else if ( $type == 9 ) {
        	$goods_array['goods_from'] = 9;
        }

        return array (
            'goodsID' => $goods_array['goodsID'],
            'postID' => $goods_array['postID'],
            'goodsName' => $goods_array['goodsName'],
            'spec' => $goods_array['spec'],
            'goods_amount' => $goods_array['goods_amount'],
            'salePrice' => $goods_array['salePrice'],
            'price' => $goods_array['price'],
            'addPoints' => $goods_array['addPoints'],
            'salePoints' => $goods_array['salePoints'],
            'goodsWeight' => $goods_array['goodsWeight'],
            'goods_from' => $goods_array['goods_from'],
            'goods_groupID' => $goods_array['goods_groupID'],
            'goods_status' => 1,
            'img_link' => $goods_array['img_link'],
            'link' => $goods_array['link'],
            'wap_link' => $goods_array['wap_link'],
            'bigCategoryID' => $goods_array['bigCategoryID'],
            'midCategoryID' => $goods_array['midCategoryID'],
            'smallCategoryID' => $goods_array['smallCategoryID'],
            'product_code' => $goods_array['product_code'],
            'twoPostID' => $goods_array['twoPostID'],
            'marketPrice' => $goods_array['marketPrice'],
            'promotion' => null
        );

    }

    public function getCartInfo( $cart_name = 'shop_cart' ) {

        //$G_SHOP->isGuest == 0（会员未登录/访客订单）
        if ($this->g_shop->isGuest)
            $bill_array = $this->g_shop->sessionCache_get($cart_name);
        else
            $bill_array = $this->g_shop->sessionCache_get($cart_name . '_' . $this->g_shop->currentPCustID, true);

        if (!$bill_array)
            $bill_array = $this->createCartStructure();

        return $bill_array;

    }

    public function setCartInfo( $bill_array, $cart_name = 'shop_cart' ) {

        if ($this->g_shop->isGuest)
            $this->g_shop->sessionCache_set($cart_name, $bill_array, G_SHOPPINGCART_TIMEOUT);
        else
            $this->g_shop->sessionCache_set($cart_name . '_' . $this->g_shop->currentPCustID, $bill_array, 0, true);

    }

    public function getCartGoodsAmount() {
        return isset($_COOKIE['cart_amount']) ? intval($_COOKIE['cart_amount']) : 0;
    }

    public function updateCartGoodsAmount( $goods_amount ) {
        setcookie('cart_amount', $goods_amount, time() + G_SHOPPINGCART_TIMEOUT * 1000, '/', G_COOKIE_DOMAIN);
    }


    /**
     * 普通商品购物车操作
     * @param int $postID 网购号
     * @param int $amount 购买数量
     * @return array
     */
    public function addGeneralGoods($postID, $goods_amount ) {

        //购物车信息
        $bill_array = $this->getCartInfo();
        $cart_array =& $bill_array['goods'];

		//实例化商品类
		$goodsHandler = new goodsHandler( $this->g_shop->DBCA );

        //判断该商品是否已经积分兑换
        if (isset($cart_array['points'][$postID])) {
        	return array( 'code' => 404, 'message' => '此商品已经积分兑换，不能再正常购买' );
        }

		//商品已在购物车里
		if (isset($cart_array['general'][$postID])) {

            $cart_array['general'][$postID]['goods_amount'] += $goods_amount;
            $cart_goods_array = $cart_array['general'][$postID];

		} else {

	        //查询商品信息
	        $arg_array = array(
	            'postID' => $postID
	        );
	        $goods_array = $goodsHandler->searchGoodsSale( $arg_array );
	        if (!$goods_array)
	            return array( 'code' => 404, 'message' => '商品信息没有找到' );

	        if ($goods_array['forsale'] == 0 || $goods_array['useFlg'] == 0)
	            return array( 'code' => 406, 'message' => '商品已下架' );
	
	
	        //购物车商品数组结构
            $goods_array['goods_amount'] = $goods_amount;
            $cart_goods_array = $this->createCartGoodsStructure( $goods_array, 1 );
            $cart_array['general'][$postID] = $cart_goods_array;

		}

        if ($cart_goods_array['goods_amount'] <= 0) {
            unset($cart_array['general'][$postID]);
        } else {

            //查询商品库存
            if (!$goodsHandler->checkGoodsStore($cart_goods_array['goodsID'], $cart_goods_array['goods_amount']))
                return array( 'code' => 406, 'message' => '商品库存不足' );

        }

        //保存购物车信息
        $cart_array['change_time'] = time();
        $this->setCartInfo( $bill_array );

        //更新购物车数量
        $cart_goods_amount = $this->getCartGoodsAmount();
        $cart_goods_amount += $goods_amount;
        $this->updateCartGoodsAmount( $cart_goods_amount );

        return array( 
        	'code' => 200, 
        	'message' => 'ok', 
        	'data' => array( 
        		'price' => $cart_goods_array['price'], 
        		'goodsName' => $cart_goods_array['goodsName'],
        		'img_link' => $cart_goods_array['img_link'],
        		'goodsAmount' => $goods_amount
        	) 
        );
		
	}
	
	/**
	 * 积分商品购物车操作
	 * @param int $postID 网购号
	 * @param int $amount 购买数量
	 * @return unknown
	 */
	public function addPointsGoods($postID, $goods_amount ) {

        global $G_SHOP;

        if (!isset($postID, $goods_amount) || !is_numeric($postID) || !is_numeric($goods_amount))
            return array( 'code' => 400, 'message' => '参数错误' );

        //购物车数组
        if ($G_SHOP->isGuest)
            $cart_array = $G_SHOP->sessionCache_get('shop_cart');
        else
            $cart_array = $G_SHOP->sessionCache_get('shop_cart_' . $G_SHOP->currentPCustID, true);

        //购物车商品数量
		$cart_goods_amount = isset($_COOKIE['cart_amount']) ? intval($_COOKIE['cart_amount']) : 0;


		//实例化商品类
		$goodsHandler = new goodsHandler( $G_SHOP->DBCA );


        //实例化公共类
        $commHandler = new commHandler( $G_SHOP->DBCA );
		
        //判断该商品是否已经正常购买
        if (isset($cart_array['general'][$postID])) {
        	return array( 'code' => 404, 'message' => '此商品已经正常购买，不能再积分兑换' );
        }

		//商品已在购物车里
		if (isset($cart_array['points'][$postID])) {
			
            $cart_array['points'][$postID]['goodsAmount'] += $goods_amount;

            if ($cart_array['points'][$postID]['goodsAmount'] <= 0)
			    unset($cart_array['points'][$postID]);

		} else {

	        //查询商品信息
	        $arg_array = array(
	            'postID' => $postID
	        );
	        $goods_array = $goodsHandler->searchGoodsSale( $arg_array );
	        if (!$goods_array)
	            return array( 'code' => 404, 'message' => '商品信息没有找到' );

	        if ($goods_array['forsale'] == 0 || $goods_array['useFlg'] == 0)
	            return array( 'code' => 406, 'message' => '商品已下架' );
			
			if ($goods_array['pointsByFlg'] != 1 || $goods_array['addPoints'] <= 0) {
				return array( 'code' => 406, 'message' => '此商品不是积分商品，不能兑换' );
			}
			
	        //购物车商品数组结构
            $goods_array['goodsAmount'] = $goods_amount;
            $goods_array['price'] = $goods_array['salePrice'];
	        $cart_goods_array = $this->createCartGoodsStructure( $goods_array );
	        $cart_array['points'][$postID] = $cart_goods_array;
	
		}

        //查询商品库存
        $store_arg_array = array(
            'storeID' => $commHandler->getStoreID(),
            'goodsID' => $cart_array['points'][$postID]['goodsID']
        );
        $goods_store_array = $commHandler->search($store_arg_array, 'wms_goodsstore');
        if (!$goods_store_array || $goods_store_array[0]->enableSaleAmount < $cart_array['points'][$postID]['goodsAmount'])
            return array( 'code' => 406, 'message' => '商品库存不足' );

        //保存购物车数组
        if ($G_SHOP->isGuest)
            $G_SHOP->sessionCache_set('shop_cart', $cart_array, G_SHOPPINGCART_TIMEOUT);
        else
            $G_SHOP->sessionCache_set('shop_cart_' . $G_SHOP->currentPCustID, $cart_array, 0, true);

        $this->cartChangeTime();


		$cart_goods_amount += $goods_amount;
		setcookie('cart_amount', $cart_goods_amount, time() + G_SHOPPINGCART_TIMEOUT * 1000, '/', G_COOKIE_DOMAIN);

        return array( 'code' => 200, 'message' => 'ok', 'data' => array( 'price' => $cart_array['general'][$postID]['price'] ) );
		
	}

    /**
     * 删除购物车商品
     * @param int $postID 三级网购号
     * @return array
     */
    public function delGeneralGoods( $postID ) {

        global $G_SHOP;

        //购物车信息
        $bill_array = $this->getCartInfo();
        $cart_array =& $bill_array['goods'];

        $goods_amount = 0;

        //商品已在购物车里
        if (isset($cart_array['general'][$postID])) {

            $goods_amount = $cart_array['general'][$postID]['goods_amount'];
            unset($cart_array['general'][$postID]);

        }

        if (empty($cart_array['general']))
            unset($cart_array['general']);

        //更新购物车信息
        $bill_array['change_time'] = time();
        $this->setCartInfo( $bill_array );

        //更新购物车数量
        $cart_goods_amount = $this->getCartGoodsAmount();
        $cart_goods_amount -= $goods_amount;
        $this->updateCartGoodsAmount( $cart_goods_amount );

        return array( 'code' => 200, 'message' => 'ok' );

    }

    /**
     * 删除购物车积分商品
     * @param int $postID 三级网购号
     * @return array
     */
    public function delPointsGoods( $postID ) {

        global $G_SHOP;
		
        if (!isset($postID) || !is_numeric($postID))
            return array( 'code' => 400, 'message' => '参数错误' );
		
        //购物车信息
        $bill_array = $this->getCartInfo();
        $cart_array =& $bill_array['goods'];

        $goods_amount = 0;

        //商品已在购物车里
        if (isset($cart_array['points'][$postID])) {

            $goods_amount = $cart_array['points'][$postID]['goods_amount'];
            unset($cart_array['points'][$postID]);

        }

        if (empty($cart_array['points']))
            unset($cart_array['points']);

        //更新购物车信息
        $bill_array['change_time'] = time();
        $this->setCartInfo( $bill_array );

        //更新购物车数量
        $cart_goods_amount = $this->getCartGoodsAmount();
        $cart_goods_amount -= $goods_amount;
        $this->updateCartGoodsAmount( $cart_goods_amount );

        return array( 'code' => 200, 'message' => 'ok' );

    }


    /**
     * 添加订单赠品
     * @param int $postID 三级网购号
     * @param int $promotionID 促销活动号
     * @param int $goods_amount 商品数量
     * @return array
     */
    public function addGiftGoods( $postID, $promotionID, $goods_amount ) {

        global $G_SHOP;

        if (!isset($postID, $promotionID, $goods_amount) || !is_numeric($postID) || !is_numeric($goods_amount) || !is_numeric($promotionID))
            return array( 'code' => 400, 'message' => '参数错误' );

        //购物车信息
        $bill_array = $this->getCartInfo();
        $cart_array =& $bill_array['goods'];

        //促销活动类
        $promotionHandler = new promotionHandler( $G_SHOP->DBCA );

        //获得购物车普通商品数组
        $p_goods_array = array();
        foreach ($cart_array['general'] as &$list) {
            $p_goods_array[] = array(
                'postID' => $list['postID'],
                'price' => $list['price'],
                'goodsAmount' => $list['goods_amount'],
            );
        }
        if (!$p_goods_array)
            return array( 'code' => 406, 'message' => '请先购买商品' );


        //查询订单赠品促销活动
        $promotion_array = $promotionHandler->searchBillPromotion( $p_goods_array, $promotionID );
        if (empty($promotion_array) || !isset($promotion_array['meet']) || empty($promotion_array['meet'][$promotionID]['gift']))
            return array( 'code' => 404, 'message' => '促销活动不存在或未生效' );
        $gift_array =& $promotion_array['meet'][$promotionID]['gift'];


        //获得赠品商品信息
        $goods_array = null;
        foreach($gift_array as &$g) {
            if ($g['postID'] == $postID)
                $goods_array = $g;
        }
        if (is_null($goods_array))
            return array( 'code' => 406, 'message' => '赠品不在当前促销活动中' );


        //保存的赠品购物车中
        if (isset($cart_array['gift'][$promotionID.$postID])) {

            $temp_array =& $cart_array['gift'][$promotionID.$postID];
            ++$temp_array['goods_amount'];
            if ($temp_array['goods_amount'] > $promotion_array['meet'][$promotionID]['multiple'])
                return array( 'code' => 406, 'message' => '超出可领取数量' );

        } else {

            $goods_array['goods_amount'] = $goods_amount;
            if ($goods_array['price'] > 0) {
                $goods_array['goods_from'] = 5;
            } else {
                $goods_array['goods_from'] = 4;
            }
            $goods_array['goods_groupID'] = $promotionID;
            $cart_goods_array = $this->createCartGoodsStructure( $goods_array, 2 );
            $cart_array['gift'][$promotionID.$postID] = $cart_goods_array;

        }


        //保存购物车信息
        $cart_array['change_time'] = time();
        $this->setCartInfo( $bill_array );

        //更新购物车数量
        $cart_goods_amount = $this->getCartGoodsAmount();
        $cart_goods_amount += $goods_amount;
        $this->updateCartGoodsAmount( $cart_goods_amount );

        return array( 'code' => 200, 'message' => 'ok' );

    }


    /**
     * 删除购物车商品
     * @param int $postID 三级网购号
     * @param int $promotionID 促销活动ID
     * @return array
     */
    public function delGift( $postID, $promotionID ) {

        global $G_SHOP;

        if (!isset($postID, $promotionID) || !is_numeric($postID) || !is_numeric($promotionID))
            return array( 'code' => 400, 'message' => '参数错误' );

        //购物车信息
        $bill_array = $this->getCartInfo();
        $cart_array =& $bill_array['goods'];

        $goods_amount = 0;

        //商品已在购物车里
        if (isset($cart_array['gift'][$promotionID . $postID])) {

            $goods_amount -= $cart_array['gift'][$promotionID . $postID]['goods_amount'];

            unset($cart_array['gift'][$promotionID . $postID]);

        }

        if (empty($cart_array['gift']))
            unset($cart_array['gift']);

        //保存购物车信息
        $cart_array['change_time'] = time();
        $this->setCartInfo( $bill_array );

        //更新购物车数量
        $cart_goods_amount = $this->getCartGoodsAmount();
        $cart_goods_amount -= $goods_amount;
        $this->updateCartGoodsAmount( $cart_goods_amount );

        return array( 'code' => 200, 'message' => 'ok' );

    }



    /**
     * 添加闪购商品
     * @param int kill_id 闪购ID
     * @return array
     */
    public function addKillGoods( $kill_id ,$goods_amount) {

        if (!isset($kill_id ) || !is_numeric($kill_id) ) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        try {

            $this->g_shop->DBCA->beginTransaction();

            //更新闪购商品已购买数量
            $update_sql = 'UPDATE promotion_secondkill SET saled_amount = saled_amount + ? WHERE kill_id = ?';
            $this->g_shop->DBCA->stmt_query($update_sql, 'ii', $goods_amount, $kill_id);


            //促销活动类实例
            $promotionHandler = new promotionHandler( $this->g_shop->DBCA );


            //查询闪购信息
            $params_array = array(
                'kill_id' => $kill_id,
                'useFlg' => 1
            );
            $kill_all_array = $promotionHandler->searchSeconKillList($params_array);

            //检查闪购活动
            if (!$kill_all_array) {
                throw new Exception('闪购活动不存在或未生效', 404);
            }
            $kill_array = &$kill_all_array[0];

            if ($kill_array['startDate'] . ' ' . $kill_array['startTime'] . ':00:00' > $this->g_shop->sys_datetime) {
                throw new Exception('闪购活动未开始', 404);
            }

            if ($kill_array['endDate'] . ' 23:59:59' < $this->g_shop->sys_datetime) {
                throw new Exception('闪购活动已结束', 404);
            }

            if ($kill_array['saled_amount'] > $kill_array['max_sale_amount']) {
                throw new Exception('闪购商品已抢完', 404);
            }

            //检查会员是否已购买该闪购商品
            $cust_log_obj = new entity('promotion_secondkill_cust_log');
            $cust_log_obj->pcustID = $this->g_shop->currentPCustID;
            $cust_log_obj->kill_id = $kill_id;
            if ($this->g_shop->DBCA->fetch($cust_log_obj)) {
                throw new Exception('不能重复购买闪购商品', 404);
            }
            $cust_log_obj->creator = 'system';
            $this->g_shop->DBCA->save($cust_log_obj);


            //实例化商品类
            $goodsHandler = new goodsHandler( $this->g_shop->DBCA );

            //查询商品信息
            $arg_array = array(
                'postID' => $kill_array['postID']
            );
            $goods_array = $goodsHandler->searchGoodsSale( $arg_array );
            if (!$goods_array) {
                throw new Exception('闪购商品不存在', 404);
            }

            //生成购物车数组
            $bill_array = $this->getCartInfo( 'kill_cart' );
            $goods_array['goods_amount'] = $goods_amount;
            $goods_array['price'] = $kill_array['kill_price'];
            $bill_array['goods']['kill'][] = $this->createCartGoodsStructure( $goods_array, 6 );

            //保存购物车数组信息
            $this->setCartInfo( $bill_array, 'kill_cart' );

            $this->g_shop->DBCA->commit();

        } catch (Exception $e) {

            $this->g_shop->DBCA->rollBack();

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

        return array( 'code' => 200, 'message' => 'ok' );

    }
    
    /**
     * 添加闪购商品
     * @param int kill_id 闪购ID
     * @return array
     */
    public function addQuickBuy( $kill_id ,$goods_amount) {

        if (!isset($kill_id ) || !is_numeric($kill_id) ) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        //促销活动类实例
        $promotionHandler = new promotionHandler( $this->g_shop->DBCA );

        try {

            $this->g_shop->DBCA->beginTransaction();

            //更新闪购商品已购买数量
            $update_sql = 'UPDATE promotion_secondkill SET saled_amount = saled_amount + ? WHERE kill_id = ? AND max_sale_amount > saled_amount';
            $this->g_shop->DBCA->stmt_query($update_sql, 'ii', $goods_amount, $kill_id);

            //查询闪购信息
            $params_array = array(
                'kill_id' => $kill_id,
                'seckillDate' => $this->g_shop->sys_date,
                'useFlg' => 1
            );
            $kill_all_array = $promotionHandler->searchSeconKillList($params_array);

            //检查闪购活动
            if (!$kill_all_array) {
                throw new Exception('闪购活动不存在或未生效', 404);
            }
            $kill_array = &$kill_all_array[0];

            if (strtotime($kill_array['startDate']) > time()) {
                throw new Exception('闪购活动未开始', 404);
            }

            if ($kill_array['endDate'] < $this->g_shop->sys_datetime) {
                throw new Exception('闪购活动已结束', 404);
            }

            if ($kill_array['saled_amount'] > $kill_array['max_sale_amount']) {
                throw new Exception('闪购商品已抢完', 404);
            }

            //检查会员是否已购买该闪购商品
            $cust_log_obj = new entity('promotion_secondkill_cust_log');
            $cust_log_obj->pcustID = $this->g_shop->currentPCustID;
            $cust_log_obj->kill_id = $kill_id;
            if ($this->g_shop->DBCA->fetch($cust_log_obj)) {
                throw new Exception('不能重复购买闪购商品', 404);
            }
            $cust_log_obj->creator = 'system';
            $this->g_shop->DBCA->save($cust_log_obj);


            //实例化商品类
            $goodsHandler = new goodsHandler( $this->g_shop->DBCA );

            //查询商品信息
            $arg_array = array(
                'postID' => $kill_array['postID']
            );
            $goods_array = $goodsHandler->searchGoodsSale( $arg_array );
            if (!$goods_array) {
                throw new Exception('闪购商品不存在', 404);
            }

            //生成购物车数组
            $bill_array = $this->getCartInfo( 'quick_cart' );
            $goods_array['goods_amount'] = $goods_amount;
            $goods_array['price'] = $kill_array['kill_price'];
            $bill_array['goods']['quick'][0] = $this->createCartGoodsStructure( $goods_array, 6 );

            //保存购物车数组信息
            $bill_array['change_time'] = time();
            $this->setCartInfo( $bill_array, 'quick_cart' );

            $this->g_shop->DBCA->commit();

        } catch (Exception $e) {

            $this->g_shop->DBCA->rollBack();

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

        return array( 'code' => 200, 'message' => 'ok' );

    }

    /**
     * 立即购买
     * @author 刘道健
     * @param int $postID 网购号
     * @param int $amount 购买数量
     * @return unknown
     */
    public function nowBuy($postID, $goods_amount ) {

        if (!isset($postID, $goods_amount) || !is_numeric($postID) || !is_numeric($goods_amount))
            return array( 'code' => 400, 'message' => '参数错误' );


        //实例化商品类
        $goodsHandler = new goodsHandler( $this->g_shop->DBCA );


        //查询商品信息
        $arg_array = array(
            'postID' => $postID
        );
        $goods_array = $goodsHandler->searchGoodsSale( $arg_array );
        if (!$goods_array)
            return array( 'code' => 404, 'message' => '商品信息没有找到' );

        if ($goods_array['forsale'] == 0 || $goods_array['useFlg'] == 0)
            return array( 'code' => 406, 'message' => '商品已下架' );


        //购物车商品数组结构
        $goods_array['goods_amount'] = $goods_amount;
        $cart_goods_array = $this->createCartGoodsStructure( $goods_array );


        //查询商品库存
        if (!$goodsHandler->checkGoodsStore($cart_goods_array['goodsID'], $cart_goods_array['goods_amount']))
            return array( 'code' => 406, 'message' => '商品库存不足' );

        $bill_array = $this->getCartInfo('now_buy');
        $bill_array['goods']['general'][0] = $cart_goods_array;

        $this->setCartInfo($bill_array, 'now_buy');

        return array( 'code' => 200, 'message' => 'ok', 'data' => array( 'price' => $cart_goods_array['price'] ) );

    }
	/**
     * 删除购物车操作【超值选购】
     * @param array $arg_array 参数数组
     */
    public function delChoiceGoods( $arg_array ) {
    	
    	//检查参数
    	if (!isset($arg_array['goodsChoiceID']) || !is_numeric($arg_array['goodsChoiceID'])) {
    		return array( 'code' => 400, 'message' => '参数错误' );
    	}
    	
        //获取积分换购商品数组
        $bill_array = $this->getCartInfo();
		
        //实例化商品类
        $goodsHandler = new goodsHandler( $this->g_shop->DBCA );

        //实例化公共类
        $commHandler = new commHandler( $this->g_shop->DBCA );
        
        
        if (isset($bill_array['goods']['choice'][$arg_array['goodsChoiceID']]) && !empty($bill_array['goods']['choice'][$arg_array['goodsChoiceID']])) {
        	unset($bill_array['goods']['choice'][$arg_array['goodsChoiceID']]);
        } else {
        	return array( 'code' => 400, 'message' => '购物车中不存在该优惠活动！');
        }
        
        //保存购物车数组信息
        $bill_array['change_time'] = time();
        $this->setCartInfo( $bill_array );
        
        return array( 'code' => 200, 'message' => 'ok');
    }
    /**
     * 购物车操作【超值选购】
     * @param array $arg_array 参数数组
     */
    public function addChoiceGoods( $arg_array ) {
    	
    	//检查参数
    	if (!isset($arg_array['goodsChoiceID']) || !is_numeric($arg_array['goodsChoiceID'])) {
    		return array( 'code' => 400, 'message' => '参数错误' );
    	}
    	
    	if (!isset($arg_array['goods']) || empty($arg_array['goods'])) {
    		return array( 'code' => 400, 'message' => '请选择该超值选购商品' );
    	}
    	
    	//实例化促销类
    	$promotionHandler = new promotionHandler( $this->g_shop->DBCA );
    	
    	$arg_select_array = array(
    		'goodsChoiceID' => $arg_array['goodsChoiceID'], //超值选购ID
    		'startDate' => $this->g_shop->sys_datetime  //当前日期
    	);
    	
    	//查询超值选购详情
    	$choice_result = $promotionHandler->searchPromotionSelection( $arg_select_array );
    	if (!isset($choice_result[0]) || empty($choice_result[0])) {
    		return array( 'code' => 400, 'message' => '该超值选购不存在' );
    	} else {
    		$choice_result = $choice_result[0];
    	}
    	
    	//判断选择的商品数量是否是限定数量
    	if (count($arg_array['goods']) != $choice_result['goodsCount']) {
    		return array( 'code' => 400, 'message' => '你只能选择 '.$choice_result['goodsCount'].' 件商品' );
    	}
    	
    	//获取有效的商品postID
    	$valid_postID_array = array();
    	foreach ($choice_result['goods'] as $goods) {
    		$valid_postID_array[] = $goods['postID'];
    	}
    	
    	//判断选择的商品是否有效
    	foreach ($arg_array['goods'] as $goods) {
    		if (!in_array($goods['postID'],$valid_postID_array)) {
    			return array( 'code' => 400, 'message' => $goods['goodsName'] . '是无效商品' );
    		}
    	}
    	
        //获取积分换购商品数组
        $bill_array = $this->getCartInfo();
		
        //实例化商品类
        $goodsHandler = new goodsHandler( $this->g_shop->DBCA );

        //实例化公共类
        $commHandler = new commHandler( $this->g_shop->DBCA );
        
        
        if (isset($bill_array['goods']['choice'][$arg_array['goodsChoiceID']]) && !empty($bill_array['goods']['choice'][$arg_array['goodsChoiceID']])) {
        	return array( 'code' => 400, 'message' => '该优惠活动已加入购物车了！');
        }
        
        //购物车数组中没有该超值选购
        foreach ($arg_array['goods'] as &$goods) {
        	
        	//查询商品信息
            $arg_sale_array = array(
                'postID' => $goods['postID']
            );
            $goods_array = $goodsHandler->searchGoodsSale( $arg_sale_array );
            
            $goods_array['goods_amount'] = $goods['goodsCount'];
            
            if (!$goods_array)
                return array( 'code' => 404, 'message' => '商品信息没有找到' );

            if ($goods_array['forsale'] == 0 || $goods_array['useFlg'] == 0)
                return array( 'code' => 406, 'message' => '商品已下架' );
			
            //查询商品库存
            $store_arg_array = array(
                'storeID' => $commHandler->getStoreID(),
                'goodsID' => $goods_array['goodsID']
            );
            $goods_store_array = $commHandler->search($store_arg_array, 'wms_goodsstore');
            if (!$goods_store_array || $goods_store_array[0]->enableSaleAmount < 1){
                return array( 'code' => 406, 'message' => '商品库存不足' );
            }
			
            $goods = $this->createCartGoodsStructure( $goods_array, 9 );
        }
        
        $choice_result['group_amount'] = 1;  //超值选购组合数量
        $choice_result['goods'] = $arg_array['goods'];
        $bill_array['goods']['choice'][$choice_result['goodsChoiceID']] = $choice_result;
		        
        
        //保存购物车数组信息
        $bill_array['change_time'] = time();
        $this->setCartInfo( $bill_array );
        
        return array( 'code' => 200, 'message' => 'ok');
    }


    /**
     * 删除购物车超值选购/套装
     * @param int key
     * @return array
     */
    public function delGroup( $key ) {

        global $G_SHOP;

        if (!isset($key) || !is_numeric($key) )
            return array( 'code' => 400, 'message' => '参数错误' );

        //购物车数组
        if ($G_SHOP->isGuest)
            $cart_array = $G_SHOP->sessionCache_get('shop_cart');
        else
            $cart_array = $G_SHOP->sessionCache_get('shop_cart_' . $G_SHOP->currentPCustID, true);

        //购物车商品数量
        $cart_goods_amount = isset($_COOKIE['cart_amount']) ? intval($_COOKIE['cart_amount']) : 0;

        //商品已在购物车里
        if (isset($cart_array['group'][$key])) {

            $cart_goods_amount -= $cart_array['group'][$key]['goods_amount'];

            unset($cart_array['group'][$key]);

        }

        if (empty($cart_array['group']))
            unset($cart_array['group']);

        //保存购物车数组
        if ($G_SHOP->isGuest)
            $G_SHOP->sessionCache_set('shop_cart', $cart_array, G_SHOPPINGCART_TIMEOUT);
        else
            $G_SHOP->sessionCache_set('shop_cart_' . $G_SHOP->currentPCustID, $cart_array, 0, true);

        $this->cartChangeTime();

        setcookie('cart_amount', $cart_goods_amount, time() + G_SHOPPINGCART_TIMEOUT * 1000, '/', G_COOKIE_DOMAIN);

        return array( 'code' => 200, 'message' => 'ok' );

    }
    
    /**
     * 组合商品加入购物车
     * @param int $recom_id 商品推荐ID
     * @param array $goodsArr 推荐商品SKU组成的数组
     * @param int $group_num 商品组合数量
     * $goodsArr = array(10437-000-5 , 10434-000-5 , 10443-000-5 , ......)
     * @return array
     */
    public function addGroupGoods($recom_id, $goodsArr, $group_amount ) {

        if (!isset($recom_id,$goodsArr) || empty($recom_id) ) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        if( !isset($goodsArr[0]) )
            return array( 'code' => 400, 'message' => '请至少选择一件组合商品' );
            
        if ( $group_amount < 1 ) {
            return array( 'code' => 400, 'message' => '请选择至少一组商品组合' );
        }

        quanli_include('module/base/promotionHandler.class.php');

        //购物车信息
        $bill_array = $this->getCartInfo();
        $cart_array =& $bill_array['goods'];

        //实例化商品类
        $goodsHandler = new goodsHandler( $this->g_shop->DBCA );

        //实例化促销类
        $promotionHandler = new promotionHandler( $this->g_shop->DBCA  );

        //组合商品数组
        $group_goods_array = array(
            'detail' => array( //组合信息
                'id' => $recom_id,
                'name' => '',
                'group_amount' => $group_amount,  //初始值
                'total_amount' => 0,
                'total_sale' => 0,    //总商品价格
                'total_price' => 0    //总商品实售价格
            ),
            'goods' => array() //商品信息
        );

        //查询推荐信息
        $recom_array = array( 'recom_id'=> $recom_id);
        $recomInfo   = $promotionHandler->searchGoodsRecommend( $recom_array );

        if( !$recomInfo )
            return array( 'code' => 404, 'message' => '组合商品信息没有找到' );

        //查询主商品信息
        $arg_array = array(
            'product_code' =>  $recomInfo[0]['product_code']
        );

        $main_goods_array = $goodsHandler->searchGoodsSale( $arg_array );
        if (!$main_goods_array)
            return array( 'code' => 404, 'message' => '组合商品信息没有找到' );
            
        //查看购物车中是否有该商品组合
        $flg = 0; //组合在购物车中存在标记 0：不存在 1：存在
        
        if (isset($cart_array['group']) && !empty($cart_array['group'])) {  //判断购物车中是否有组合商品
        	
        	$temp_goods_array = array_merge($goodsArr,array($recomInfo[0]['product_code']));
        	
        	foreach ($cart_array['group'] as &$group) {
        		
        		//判断组合ID和商品数量是否相同
        		if ($group['detail']['id'] == $recom_id && count($temp_goods_array) == count($group['goods'])) {
        			$flg = 1; //假如选择的组合与当前组合相同
    				foreach ($group['goods'] as $goods) {
						if (!in_array($goods['product_code'],$temp_goods_array)) {
							$flg = 0;
						}
        			}
        		}
        		
        		//该组合在商品中已经存在 
        		if ($flg == 1) {
        			
        			//改变商品组合的数量
					$group['detail']['group_amount'] += $group_amount;
					
					//返回选择显示的结果
					$returnData = $group;
					
					break;
				}
        	}
        }
        
        //不存在该商品组合
		if ($flg == 0) {

	        //购物车商品数组结构
	        $main_goods_array['goods_amount'] = 1;
	        $main_goods_array['goods_groupID'] = $recom_id;           //推荐ID
	        $main_goods_array['price'] = $recomInfo[0]['mainPrice'];  //主商品实售价格
	
	        $group_goods_array['goods'][] = $this->createCartGoodsStructure( $main_goods_array, 3 );
	        ++$group_goods_array['detail']['total_amount']; //总商品数量加1
	        $group_goods_array['detail']['total_price'] += $recomInfo[0]['mainPrice']; //加入主商品实售价格
	        $group_goods_array['detail']['total_sale'] += $main_goods_array['marketPrice']; //加入主商品价格
	
	        //查询推荐活动商品信息
	        $recom_detail_array =array('recom_id'=>$recom_id);
	        $recommendDetail = $promotionHandler->searchGoodsRecommendDetail( $recom_detail_array );
	
	        if( !$recommendDetail )
	            return array( 'code' => 404, 'message' => '组合商品信息没有找到' );
	
	        //循环检查推荐商品
	        foreach ( $recommendDetail as $detail ){
	
	            if( in_array( $detail['product_code'] , $goodsArr )  ){
	
	                //查询商品信息
	                $arg_array = array(
	                    'product_code' => $detail['product_code']
	                );
	                $goods_array = $goodsHandler->searchGoodsSale( $arg_array );
	
	                if (!$goods_array)
	                    return array( 'code' => 404, 'message' => '组合商品信息没有找到' );
	
	                ++$group_goods_array['detail']['total_amount']; //总商品数量加1
	                $group_goods_array['detail']['total_price'] += $detail['sale_price'];  //加入该推荐商品的实售价格
	                $group_goods_array['detail']['total_sale'] += $goods_array['marketPrice']; //加入该推荐商品的销售价格
	
	                //购物车商品数组结构
	                $goods_array['goods_amount'] = 1;
	                $goods_array['goods_groupID'] = $recom_id;   //推荐ID
	                $goods_array['price'] = $detail['sale_price'];  //推荐商品实售价格
	                $group_goods_array['goods'][] = $this->createCartGoodsStructure( $goods_array, 3 );
	
	            }
	
	        }
	
	        if( $group_goods_array['detail']['total_amount'] == 1 )
	            return array( 'code' => 404, 'message' => '组合商品信息有误' );
	
	        //将组合商品信息放入group中
	        $cart_array['group'][] = $group_goods_array;
	        
	        //将商品组合返回显示
	        $returnData = $group_goods_array;
	        
		}
        //保存购物车信息
        $bill_array['change_time'] = time();
        $this->setCartInfo( $bill_array );

        //更新购物车数量
        $cart_goods_amount = $this->getCartGoodsAmount();
        $cart_goods_amount += $group_goods_array['detail']['total_amount'];
        $this->updateCartGoodsAmount( $cart_goods_amount );

        return array( 'code' => 200, 'message' => 'ok', 'data' => $returnData );
		
    }

    /**
     * 添加积分换购商品
     * @param array $arg_array 参数数组
     * @return array
     */
    public function pointsGoodsAdd( $arg_array ) {
		
        if (!isset($arg_array['postID']) || !is_numeric($arg_array['postID']) ) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        if( !isset($arg_array['goods_amount']) || !is_numeric($arg_array['goods_amount'])) {
            return array( 'code' => 400, 'message' => '请选择换购的商品' );
        }
		
        //获得会员积分
        $points_array = $this->g_shop->EAI->memberAccount( $this->g_shop->currentPCustID, G_PAYTYPE_POINTS, $this->g_shop->DBCA );
        
        if ($points_array['code'] == 200 && isset($points_array['data']['useableAccount'])) {
            $userPoints = $points_array['data']['useableAccount'];
        } else {
            $userPoints = 0;
        }
        
        //获取积分换购商品数组
        $bill_array = $this->getCartInfo();
		
        //实例化商品类
        $goodsHandler = new goodsHandler( $this->g_shop->DBCA );

        //实例化公共类
        $commHandler = new commHandler( $this->g_shop->DBCA );
        
        quanli_require('module/base/promotionHandler.class.php');
        
        //实例化促销类
        $promotionHandler = new promotionHandler( $this->g_shop->DBCA );

        //统计换购商品总共需多少积分
        $totalPoints = 0;
        
        if (isset($bill_array['goods']['points'][$arg_array['postID']])) { //商品已在购物车中
        	
        	$bill_array['goods']['points'][$arg_array['postID']]['goods_amount'] += $arg_array['goods_amount'];
        	
        	$totalPoints = $bill_array['goods']['points'][$arg_array['postID']]['addPoints'] * $bill_array['goods']['points'][$arg_array['postID']]['goods_amount'];
			
        	$goodsPoints = $bill_array['goods']['points'][$arg_array['postID']]['addPoints'] * $arg_array['goods_amount']; //当前商品总积分
        	
        } else {
        	
			//获取商品postID
        	$postID = $arg_array['postID'];
        	
            //查询商品信息
            $arg_sale_array = array(
                'postID' => $postID
            );
            $goods_array = $goodsHandler->searchGoodsSale( $arg_sale_array );
			
            //检查该商品是否为积分商品
        	$arg_points_array = array(
        		'id' => $goods_array['product_code'],
        		'startDate' => date('Y-m-d',time())
        	);
        	
        	$points_result = $promotionHandler->validPointsMallGoods( $arg_points_array );
        	
        	if (isset($points_result[0]) && !empty($points_result[0])) {
        		$goods_array['addPoints'] = $points_result[0]['points'];
        		$goods_array['pointPrice'] = $points_result[0]['pointsPrice'];
        	}
        	//检查该商品是否为积分商品 end
            
            if (!$goods_array)
                return array( 'code' => 404, 'message' => '商品信息没有找到' );

            if ($goods_array['forsale'] == 0 || $goods_array['useFlg'] == 0)
                return array( 'code' => 406, 'message' => '商品已下架' );

            if ( $goods_array['addPoints'] <= 0) {
                return array( 'code' => 406, 'message' => '商品不是积分商品，不能兑换' );
            }
            
            //购物车中总积分
            $totalPoints += $goods_array['addPoints'] * $arg_array['goods_amount'];
            
            //当前商品总积分
            $goodsPoints = $goods_array['addPoints'] * $arg_array['goods_amount'];

            //查询商品库存
            $store_arg_array = array(
                'storeID' => $commHandler->getStoreID(),
                'goodsID' => $goods_array['goodsID']
            );
            $goods_store_array = $commHandler->search($store_arg_array, 'wms_goodsstore');
            if (!$goods_store_array || $goods_store_array[0]->enableSaleAmount < 1)
                return array( 'code' => 406, 'message' => '商品库存不足' );

            $goods_array['goods_amount'] = $arg_array['goods_amount'];  //购买数量
            $goods_array['price'] = $goods_array['pointPrice'];			//积分商品价格
            $bill_array['goods']['points'][$postID] = $this->createCartGoodsStructure( $goods_array, 9 );
			
        }
		
        if( $userPoints < $totalPoints ) {
        	
        	if ($totalPoints == $goodsPoints) { //购物车中没有积分商品
        		$error_msg = '您的良票不足<br>当前换购商品总良票为：' . $goodsPoints . '<br/>您的剩余良票为：' . $userPoints . '<br/>';
        	} else {
        		$error_msg = '您的良票不足<br>当前换购商品总良票为：' . $goodsPoints . '<br/>购物车中商品总良票：' . ($totalPoints-$goodsPoints) . '<br/>您的剩余良票为：' . $userPoints . '<br/>';
        	}
        	
            return array( 'code' => 406, 'message' => $error_msg );
        }
        //保存购物车数组信息
        $bill_array['change_time'] = time();
        $this->setCartInfo( $bill_array );
        
        return array( 
        	'code' => 200, 
        	'message' => 'ok', 
        	'data' => array(
	        	'price' => $bill_array['goods']['points'][$arg_array['postID']]['price'],
	        	'addPoints' => $bill_array['goods']['points'][$arg_array['postID']]['addPoints'],
	    		'goodsName' => $bill_array['goods']['points'][$arg_array['postID']]['goodsName'],
	    		'img_link' => $bill_array['goods']['points'][$arg_array['postID']]['img_link'],
	    		'goodsAmount' => $arg_array['goods_amount']
	    		) 
	    	);

    }
    
    /**
     * 更新组合商品
     * @param int $index 组合商品数组索引
     * @param int $groupAmount 组合数量
     */
    public function updateGroupGoods( $index , $groupAmount ){

        if (!isset($index , $groupAmount) || !is_numeric($index) || !is_numeric($groupAmount) ) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        //购物车信息
        $bill_array = $this->getCartInfo();
        $cart_array =& $bill_array['goods'];

        //商品数量
        $goods_amount = 0;

        //组合已在购物车里
        if (isset($cart_array['group'][$index])) {

            $cart_array['group'][$index]['detail']['group_amount'] += $groupAmount;

        } else {

            return array( 'code' => 400, 'message' => '组合商品信息没找到' );

        }

        if ( $cart_array['group'][$index]['detail']['total_amount'] <= 0) {
            unset($cart_array['group'][$index]);
        }else{
            $goods_amount = $cart_array['group'][$index]['detail']['total_amount'] * $groupAmount;  //组合中的商品总数*组合数量
        }

        //保存购物车信息
        $bill_array['change_time'] = time();
        $this->setCartInfo( $bill_array );

        //更新购物车数量
        $cart_goods_amount = $this->getCartGoodsAmount();
        $cart_goods_amount += $goods_amount;
        $this->updateCartGoodsAmount( $cart_goods_amount );

        return array( 'code' => 200, 'message' => 'ok', 'data' => array( 'price' => $cart_array['group'][$index]['detail']['group_amount'] * $cart_array['group'][$index]['detail']['total_price'] ) );

    }
    
    /**
     * 删除组合商品
     * @param int $index 组合商品数组索引
     */
    public function delGroupGoods( $index ){

        if (!isset($index) || !is_numeric($index) ) {
            return array( 'code' => 400, 'message' => '参数错误' );
        } 

        global $G_SHOP;

        //购物车信息
        $bill_array = $this->getCartInfo();
        $cart_array =& $bill_array['goods'];

        $goods_amount = 0;

        //商品已在购物车里
        if (isset($cart_array['group'][$index])) {

            //获取该组合中的总商品数量（组合数量*组合中商品总数）
            $goods_amount = $cart_array['group'][$index]['detail']['group_amount'] * $cart_array['group'][$index]['detail']['total_amount'];
            unset($cart_array['group'][$index]);

        }

        if (empty($cart_array['group']))
            unset($cart_array['group']);

        //更新购物车信息
        $bill_array['change_time'] = time();
        $this->setCartInfo( $bill_array );

        //更新购物车数量
        $cart_goods_amount = $this->getCartGoodsAmount();
        $cart_goods_amount -= $goods_amount;
        $this->updateCartGoodsAmount( $cart_goods_amount );

        return array( 'code' => 200, 'message' => 'ok' );

    }

}
